package com.keba.lamp.complaint.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.keba.basic.base.service.impl.SuperServiceImpl;
import com.keba.basic.context.ContextUtil;
import com.keba.basic.utils.ArgumentAssert;
import com.keba.lamp.complaint.entity.EvidenceComponentCaseTypeRel;
import com.keba.lamp.complaint.manager.EvidenceComponentCaseTypeRelManager;
import com.keba.lamp.complaint.service.EvidenceComponentCaseTypeRelService;
import com.keba.lamp.complaint.service.EvidenceComponentService;
import com.keba.lamp.complaint.vo.result.EvidenceComponentResultVO;
import com.keba.lamp.complaint.vo.result.EvidenceResultVO;
import com.keba.lamp.complaint.vo.save.EvidenceComponentCaseTypeRelSaveVO;
import com.keba.lamp.complaint.vo.update.EvidenceComponentCaseTypeRelUpdateVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 案件类型和组件库关系表（证据目录）
 * </p>
 *
 * @author chaowu.wang
 * @date 2025-03-27 22:17:56
 * @create [2025-03-27 22:17:56] [chaowu.wang] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EvidenceComponentCaseTypeRelServiceImpl extends SuperServiceImpl<EvidenceComponentCaseTypeRelManager, Long, EvidenceComponentCaseTypeRel> implements EvidenceComponentCaseTypeRelService {

    private final EvidenceComponentService evidenceComponentService;

    @Override
    protected <SaveVO> EvidenceComponentCaseTypeRel saveBefore(SaveVO saveVO) {

        EvidenceComponentCaseTypeRelSaveVO relSaveVO = (EvidenceComponentCaseTypeRelSaveVO) saveVO;
        EvidenceComponentCaseTypeRel oldTypeAndCaseType = superManager.getByBizTypeAndCaseType(relSaveVO.getBizType(), relSaveVO.getCaseType(), ContextUtil.getTenantId());
        ArgumentAssert.isNull(oldTypeAndCaseType, "业务类型和案件类别已存在");
        if (StringUtils.isBlank(relSaveVO.getCode())) {
            //租户证据目录和公共证据目编码保持一致
            String maxCode = this.superManager.selectMaxCode();
            if (StringUtils.isNotBlank(maxCode)) {
                relSaveVO.setCode(String.valueOf(Integer.parseInt(maxCode) + 1));
            } else {
                relSaveVO.setCode("2000");
            }
        }
        List<EvidenceComponentResultVO> componentList = relSaveVO.getComponentList();
        if (CollectionUtil.isNotEmpty(componentList)) {
            relSaveVO.setComponentId(componentList.stream().map(
                    EvidenceComponentResultVO::getId
            ).map(String::valueOf).collect(Collectors.joining(",")));
        }
        relSaveVO.setTenantId(ContextUtil.getTenantId());
        return super.saveBefore(saveVO);
    }

    @Override
    protected <UpdateVO> EvidenceComponentCaseTypeRel updateBefore(UpdateVO updateVO) {
        EvidenceComponentCaseTypeRelUpdateVO relUpdateVO = (EvidenceComponentCaseTypeRelUpdateVO) updateVO;
        List<EvidenceComponentResultVO> componentList = relUpdateVO.getComponentList();
        if (CollectionUtil.isNotEmpty(componentList)) {
            relUpdateVO.setComponentId(componentList.stream().map(
                    EvidenceComponentResultVO::getId
            ).map(String::valueOf).collect(Collectors.joining(",")));
        }
        relUpdateVO.setTenantId(ContextUtil.getTenantId());
        return super.updateBefore(updateVO);
    }

    @Override
    public <UpdateVO> EvidenceComponentCaseTypeRel updateById(UpdateVO updateVO) {
        EvidenceComponentCaseTypeRelUpdateVO relUpdateVO = (EvidenceComponentCaseTypeRelUpdateVO) updateVO;
        EvidenceComponentCaseTypeRel entity = this.getById(relUpdateVO.getId());
        ArgumentAssert.notNull(entity, "未找到对应的证据目录");
        Long tenantId = ContextUtil.getTenantId();
        //修改时，原租户与当前租户不匹配，新增一条记录
        if (!Objects.equals(entity.getTenantId(), tenantId)) {
            EvidenceComponentCaseTypeRelSaveVO saveVO = new EvidenceComponentCaseTypeRelSaveVO();
            BeanUtils.copyProperties(updateVO, saveVO);
            saveVO.setTenantId(ContextUtil.getTenantId());
            return super.save(saveVO);
        } else {
            EvidenceComponentCaseTypeRel oldTypeAndCaseType = superManager.getByBizTypeAndCaseType(relUpdateVO.getBizType(), relUpdateVO.getCaseType(), ContextUtil.getTenantId());
            ArgumentAssert.isTrue(Objects.isNull(oldTypeAndCaseType) || Objects.equals(oldTypeAndCaseType.getId(), relUpdateVO.getId()),
                    "业务类型和案件类别已存在");
            relUpdateVO.setTenantId(ContextUtil.getTenantId());
            return super.updateById(updateVO);
        }
    }

    @Override
    public List<EvidenceResultVO> queryEvidenceCaseTypeRel(String bizType, String caseType) {
        EvidenceComponentCaseTypeRel caseTypeRel = superManager.getByBizTypeAndCaseType(bizType, caseType, ContextUtil.getTenantId());
        if (Objects.nonNull(caseTypeRel) && StringUtils.isNotBlank(caseTypeRel.getComponentId())) {
            String componentIds = caseTypeRel.getComponentId();
            List<Long> componentIdList = Arrays.stream(componentIds.split(",")).map(Long::valueOf).collect(Collectors.toList());
            List<EvidenceComponentResultVO> componentResultVOList = evidenceComponentService.getComponentByIds(componentIdList);
            Map<Long, EvidenceComponentResultVO> componentResultVOMap = componentResultVOList.stream().collect(Collectors.toMap(EvidenceComponentResultVO::getId, Function.identity()));
            List<EvidenceResultVO> evidenceResultVOList = new ArrayList<>();
            for (int i = 0; i < componentIdList.size(); i++) {
                Long componentId = componentIdList.get(i);
                EvidenceComponentResultVO evidenceComponentResultVO = componentResultVOMap.get(componentId);
                EvidenceResultVO resultVO = new EvidenceResultVO();
                resultVO.setSortValue(i);
                resultVO.setComponentName(evidenceComponentResultVO.getName());
                evidenceResultVOList.add(resultVO);
            }
            Collections.sort(evidenceResultVOList, Comparator.comparingInt(EvidenceResultVO::getSortValue));
            return evidenceResultVOList;
        }
        return Collections.emptyList();
    }

}


